/*
 * @Author: 郑亮 z17620994877@163.com
 * @Date: 2024-04-09 09:29:16
 * @LastEditors: 郑亮 z17620994877@163.com
 * @LastEditTime: 2024-04-12 18:25:35
 * @FilePath: \node-koa2\module\user\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

const query = require('../../utils/db')

const { jwt } = require('../../jwt/token');

const dayjs = require('dayjs')

const fs = require('fs')

const path = require('path')
// 获取验证码
const query_auto_code = (ctx) => {
    let auto_code = ''
    for (let i = 0; i < 4; i++) {
        auto_code += Math.floor(Math.random() * (9 - 0 + 1)) + 0;
    }
    return ctx.body = {
        code: 200,
        data: auto_code,
        msg: '成功'
    }
}

// 用户注册
const user_register = async (ctx) => {
    console.log(ctx.request.body)
    const { name, password } = ctx.request.body || {}
    
    if (!name || !password) {
        return ctx.body = JSON.stringify({
            code: 0,
            data: null,
            msg: '请输入账号密码'
        })
    }
    const user_pro = new Promise(async (resolve) => {
        let writeParams = []
        const user_path = path.resolve(__dirname, '../../app_qq_data/user/user.json')
        await fs.readFile(user_path, 'utf-8', async (err, data) => {
            if (err) {
                ctx.body = JSON.stringify({
                    code: 0,
                    data: null,
                    msg: err
                })
                resolve(ctx.body)
            }
            const write_data = async () => {
                await fs.writeFile(user_path, JSON.stringify(writeParams), err => {
                    if (err) {
                        ctx.body = JSON.stringify({
                            code: 0,
                            data: null,
                            msg: err
                        })
                    } else {
                        ctx.body = JSON.stringify({
                            code: 200,
                            data: null,
                            msg: '注册成功'
                        })
                    }
                    resolve(ctx.body)
                })
            }
            if (data) {
                const user_list = JSON.parse(data) || {}
                writeParams = user_list
                const filter_user_index = user_list.findIndex(item => item.name === name);
                if (filter_user_index === -1) {
                    writeParams.push({
                        id: new Date().getTime(),
                        name,
                        password
                    })
                    await write_data()
                } else {
                    ctx.body = JSON.stringify({
                        code: 0,
                        data: null,
                        msg: '用户名已注册'
                    })
                    resolve(ctx.body)
                }
            } else {
                await write_data()
            }
        })
    })
    return await user_pro
}
const user_login = async (ctx) => {
    const { name, password } = ctx.request.body
    if (!name || !password) {
        return ctx.body = {
            code: 0,
            data: null,
            msg: '用户名密码不能为空'
        }
    }
    const user_pro = new Promise(async (resolve) => {
        const user_path = path.resolve(__dirname, '../../app_qq_data/user/user.json')
        await fs.readFile(user_path, 'utf-8', async (err, data) => {
            if (err) {
                ctx.body = JSON.stringify({
                    code: 0,
                    data: null,
                    msg: err
                })
                return resolve(ctx.body)
            }
            if (data) {
                const user_list = JSON.parse(data) || {}
                const filter_user = user_list.find(item => item.name === name);
                if (!filter_user) {
                    ctx.body = JSON.stringify({
                        code: 0,
                        data: null,
                        msg: '用户名不存在'
                    })
                }
                if (filter_user.password === password) { 
                    const token = jwt.sign({ name }, 'token')
                    ctx.body = JSON.stringify({
                        code: 200,
                        data: token,
                        msg: '登录成功'
                    })
                } else {
                    ctx.body = JSON.stringify({
                        code: 0,
                        data: null,
                        msg: '密码错误'
                    })
                }
                resolve(ctx.body)
            }
        })
    })
    return  await user_pro
}

module.exports = [{
    request: 'get',
    path: '/api/queryAutoCode',
    method: query_auto_code,
}, {
    request: 'post',
    path: '/api/login',
    method: user_login,
}, {
    request: 'post',
    path: '/api/register',
    method: user_register,
}]